//
//  WDKCViewController.m
//  Hxcsfw
//
//  Created by qiysoft on 2017/11/15.
//  Copyright © 2017年 企友软mac. All rights reserved.
//

#import "WDKCViewController.h"
#import "VideoDetailViewController.h"
#import "SchoolModel.h"
#import "UIImageView+WebCache.h"
#import "WDKCCell.h"
#define WDKCCellIndentifier @"WDKCCellIndentifier"

@interface WDKCViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    WDKCCell *cell1;
    int j;
    int pageMark;
    NSString *strChosen;
    NSInteger markTag;
}
@property (weak, nonatomic) IBOutlet UIView *lineViewL;
@property (weak, nonatomic) IBOutlet UIView *lineViewM;
@property (weak, nonatomic) IBOutlet UIView *lineViewR;
@property (weak, nonatomic) IBOutlet UIButton *btnL;
@property (weak, nonatomic) IBOutlet UIButton *btnM;
@property (weak, nonatomic) IBOutlet UIButton *btnR;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topConH;

@property (nonatomic, strong)NSMutableArray *arrClass;

@end

@implementation WDKCViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([WShareUtil sharedData].dicSleSymbol) {
        for (int i = 0; i < self.arrClass.count; i++) {
            if ([[WShareUtil sharedData].dicSleSymbol[@"id"] isEqualToString:[self.arrClass[i] strId]]) {

                SchoolModel *schoolModel = self.arrClass[i];
                if ([[WShareUtil sharedData].dicSleSymbol[@"chosen"] boolValue]) {
                    schoolModel.chosen = @"1";
                }
                [self.arrClass replaceObjectAtIndex:i withObject:schoolModel];

                [self.myTableView reloadData];
                [WShareUtil sharedData].dicSleSymbol = nil;
            }
        }
    }

    if ([WShareUtil sharedData].dicBuySymbol) {
        for (int i = 0; i < self.arrClass.count; i++) {
            if ([[WShareUtil sharedData].dicBuySymbol[@"id"] isEqualToString:[self.arrClass[i] strId]]) {

                SchoolModel *schoolModel = self.arrClass[i];
                if ([[WShareUtil sharedData].dicBuySymbol[@"boughten"] boolValue]) {
                    schoolModel.boughten = @"1";
                }
                [self.arrClass replaceObjectAtIndex:i withObject:schoolModel];

                [self.myTableView reloadData];
                [WShareUtil sharedData].dicBuySymbol = nil;
            }
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"我的课程";

    markTag = -1;
    self.arrClass = [NSMutableArray array];

    if (XIPHONE) {
        _topConH.constant = 64 + 24;
    }
    // 1.注册控件
    UINib *cellNib = [UINib nibWithNibName:@"WDKCCell" bundle:nil];
    [self.myTableView registerNib:cellNib forCellReuseIdentifier:WDKCCellIndentifier];
//    _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.prototypeCell  = [self.myTableView dequeueReusableCellWithIdentifier:WDKCCellIndentifier];

    strChosen = nil;
//    [self requestListDataStrChosen:strChosen num:@"1" isRefrsh:YES];
    [self notifyRequestListData];
    [self.myTableView.header beginRefreshing];
}

- (void)noWifiRefershingEnd {
    [self.myTableView.header endRefreshing];
    [self.myTableView.footer endRefreshing];
    [WShareUtil sharedData].isShowWait = YES;
}

- (void)notifyRequestListData{

    self.myTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self requestListDataStrChosen:strChosen num:@"1" isRefrsh:YES];
        j = 1;
    }];

    self.myTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSString *num = [NSString stringWithFormat:@"%d",++j];
        [self requestListDataStrChosen:strChosen num:num isRefrsh:NO];
    }];
}

//设置UITableViewCell的数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    cell1 = [tableView dequeueReusableCellWithIdentifier:@"WDKCCell"];
    if (cell1 == nil) {
        cell1  = [[[NSBundle mainBundle] loadNibNamed:@"WDKCCell" owner:self options:nil] lastObject];
    }
    cell1.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (self.arrClass.count > 0 && self.arrClass) {
        
//        [cell1.imgCell sd_setImageWithURL:[NSURL URLWithString:[self.arrClass[indexPath.row] imgsrc]] placeholderImage:[UIImage imageNamed:@"school_image.png"]];

        GifView *gifView = [WShareUtil animatedGifWithData:cell1.imgCell];
        [cell1.imgCell addSubview:gifView];

        [cell1.imgCell sd_setImageWithURL:[NSURL URLWithString:[self.arrClass[indexPath.row] imgsrc]] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            [gifView removeFromSuperview];
        }];

        if (pageMark == 0) {
            if ([[_arrClass[indexPath.row] chosen] boolValue]) {
                cell1.lbType.hidden = NO;
                cell1.lbType.text = @"已选课";
                cell1.lbType.backgroundColor = WRGBColor(235, 107, 12);
            } else if (![[_arrClass[indexPath.row] chosen] boolValue] && [[_arrClass[indexPath.row] boughten] boolValue] && pageMark != 1) {
                cell1.lbType.hidden = NO;
                cell1.lbType.text = @"已购买";
                cell1.lbType.backgroundColor = WRGBColor(208, 45, 39);
            }
        }

        if (pageMark == 1) {
            cell1.lbType.hidden = NO;
            cell1.lbType.text = @"已选课";
            cell1.lbType.backgroundColor = WRGBColor(235, 107, 12);
        }

        if (pageMark == 2) {
            cell1.lbType.hidden = NO;
            cell1.lbType.text = @"已购买";
            cell1.lbType.backgroundColor = WRGBColor(208, 45, 39);
        }

//        if ([[_arrClass[indexPath.row] chosen] boolValue]) {
//            cell1.lbType.hidden = NO;
//            cell1.lbType.text = @"已选课";
//            cell1.lbType.backgroundColor = WRGBColor(235, 107, 12);
//        } else if (![[_arrClass[indexPath.row] chosen] boolValue] && [[_arrClass[indexPath.row] boughten] boolValue]) {
//            cell1.lbType.hidden = NO;
//            cell1.lbType.text = @"已购买";
//            cell1.lbType.backgroundColor = WRGBColor(208, 45, 39);
//        }

        cell1.lbTitle.text = [self.arrClass[indexPath.row] strTitle];

        [UILabel changeSpaceForLabel:cell1.lbTitle];
        cell1.lbTime.text = [self.arrClass[indexPath.row] sdate];
    }
    
    return cell1;
}

//行点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    VideoDetailViewController *videoDetailVc = [[VideoDetailViewController alloc] init];
    videoDetailVc.strId = [self.arrClass[indexPath.row] strId];
    [self.navigationController pushViewController:videoDetailVc animated:YES];
}

//分组个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//列表行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrClass.count;
    
}

//设置行高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 100;
    
}

- (void)requestListDataStrChosen:(NSString *)Chosen num:(NSString *)pageNum isRefrsh:(BOOL)isRefrsh{

    [WShareUtil sharedData].isShowWait = NO;
    NSString *chosen;
    NSString *boughten;
    if ([WShareUtil strNilOrEmpty:strChosen]) {
        chosen = @"0";
        boughten = @"0";
    }else if ([strChosen isEqualToString:@"chosen"]) {
        chosen = @"1";
        boughten = @"0";
    }else {
        chosen = @"0";
        boughten = @"1";
    }

    NSDictionary *parametersDict;
    NSString *nologinuser;
    NSString *username;
    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }

        parametersDict = @{@"mode":@"native",@"service":@"mine",@"content":@{@"chosen":chosen,@"boughten":boughten,@"revert":@"mycourse",@"username":username,@"pagesize":@"10",@"pagenumber":pageNum}};
    } else {
        nologinuser = [WShareUtil getUUID];
        parametersDict = @{@"mode":@"native",@"service":@"mine",@"content":@{@"chosen":chosen,@"boughten":boughten,@"revert":@"mycourse",@"nologinuser":nologinuser,@"pagesize":@"10",@"pagenumber":pageNum}};
    }
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};
    
    
    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        
        if ([successStr isEqualToString:@"false"]) {
            return;
        }
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];
        
        if (isRefrsh) {
            [self.arrClass removeAllObjects];
        }
        
        NSArray *arrData = returnDic[@"data"];
        
        for (NSDictionary *dic in arrData) {
            SchoolModel *schoolModel = [SchoolModel mj_objectWithKeyValues:dic];
            [self.arrClass addObject:schoolModel];
        }
        [self noWifiRefershingEnd];
        [self.myTableView reloadData];
        
        ///* --- 图片式提醒
        UIView *view = [self.myTableView viewWithTag:10000];
        [view removeFromSuperview];
        HHNonePage *_nonePage = [[HHNonePage alloc]init];
        _nonePage = nil;
        if (self.arrClass.count == 0) {
            _nonePage = [[HHNonePage alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
            _nonePage.tag = 10000;
            [self.myTableView addSubview:_nonePage];
        }
        if (arrData.count < 10) {
            // 拿到当前的上拉刷新控件，变为没有更多数据的状态
            [self.myTableView.footer endRefreshingWithNoMoreData];
        }
        
    } failure:^(NSError *error) {
        [self noWifiRefershingEnd];
        WLog(@"失败");
    } showProgress:YES];
}

- (IBAction)seletBtnClick:(UIButton *)sender {

    if (markTag == sender.tag) {
        return;
    }
    if (sender.tag == 0) {
        _lineViewL.hidden = NO;
        _lineViewM.hidden = YES;
        _lineViewR.hidden = YES;
        strChosen = nil;

        [_btnL setTitleColor:[UIColor colorWithRed:0.22 green:0.59 blue:0.89 alpha:1] forState:UIControlStateNormal];
        [_btnM setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_btnR setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [self requestListDataStrChosen:strChosen num:@"1" isRefrsh:YES];
        pageMark = 0;
    } else if (sender.tag == 1) {
        _lineViewL.hidden = YES;
        _lineViewM.hidden = NO;
        _lineViewR.hidden = YES;
        strChosen = @"chosen";
        [_btnL setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_btnM setTitleColor:[UIColor colorWithRed:0.22 green:0.59 blue:0.89 alpha:1] forState:UIControlStateNormal];
        [_btnR setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];

        [self requestListDataStrChosen:strChosen num:@"1" isRefrsh:YES];
        pageMark = 1;
    } else if (sender.tag == 2) {
        _lineViewL.hidden = YES;
        _lineViewM.hidden = YES;
        _lineViewR.hidden = NO;
        strChosen = @"boughten";
        [_btnL setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_btnM setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_btnR setTitleColor:[UIColor colorWithRed:0.22 green:0.59 blue:0.89 alpha:1] forState:UIControlStateNormal];

        [self requestListDataStrChosen:strChosen num:@"1" isRefrsh:YES];

        pageMark = 2;
    }
    [self.myTableView reloadData];
    markTag = sender.tag;
}

@end
